﻿#include "Mapper_MEMSData.h"

#include <qdebug.h>
#include "qvariant.h"
#include "DataBaseConnector.h"
#include "MapperTool.h"

Mapper_MEMSData::Mapper_MEMSData()
{
setObjectName(getClassNameFirstLow<Mapper_MEMSData>());
}

Mapper_MEMSData::~Mapper_MEMSData()
{
}

bool Mapper_MEMSData::saveMEMSData(MEMSData mEMSData)
{
  QString data=mEMSData.getSourceData().toHex();
  QString dateTime=MapperTool::mysqlDateTimeString(mEMSData.getCreateTime());
  QString mysql="INSERT INTO `"+string_dataBaseName+"` SET "+string_sourceData+"='%1',"+string_createTime+"='%2';";
  mysql=mysql.arg(data).arg(dateTime);
  return dataBaseConnector->exec(mysql).lastError().type()==QSqlError::NoError?true:false;
}

QVector<MEMSData> Mapper_MEMSData::getAllMEMSData()
{
  QString mysql="SELECT "+string_sourceData+","+string_createTime+" FROM `"+string_dataBaseName+"`;";
  QSqlQuery query=dataBaseConnector->exec(mysql);
  QVector<MEMSData> dataList;
  return query.lastError().type()==QSqlError::NoError?*getList(&query,&dataList):dataList;
}

QVector<MEMSData> Mapper_MEMSData::getMEMSDataByTime(QDateTime begin,QDateTime end)
{
  QString mysql="SELECT "+string_sourceData+","+string_createTime+" FROM `"+string_dataBaseName+"` WHERE "+string_createTime+">='%1' AND "+string_createTime+"<='%2';";
  mysql=mysql.arg(MapperTool::mysqlDateTimeString(begin)).arg(MapperTool::mysqlDateTimeString(end));
  QSqlQuery query=dataBaseConnector->exec(mysql);
  QVector<MEMSData> dataList;

  return query.lastError().type()==QSqlError::NoError?*getList(&query,&dataList):dataList;
}

QVector<MEMSData> *Mapper_MEMSData::getList(QSqlQuery* query,QVector<MEMSData>* list)
{
  while (query->next())
    {
      MEMSData mEMSData;
      mEMSData.setSourceData(QByteArray::fromHex(query->value(string_sourceData).toByteArray()));
      mEMSData.setCreateTime(query->value(string_createTime).toDateTime());
      list->append(mEMSData);
    }
  return list;
}

DataBaseConnector* Mapper_MEMSData::getDataBaseConnector()
{
  return dataBaseConnector;
}

void Mapper_MEMSData::setDataBaseConnector(DataBaseConnector* dataBaseConnector)
{
  this->dataBaseConnector=dataBaseConnector;
  printInjection(this,dataBaseConnector);
}

void Mapper_MEMSData::objectAutoInjection(QHash<QString, QObject *> *objMap)
{
  setDataBaseConnector(getObjFromMap<DataBaseConnector>(objMap));
}
